package app

import (
	"encoding/json"
	"golang-blog/helper"
	"golang-blog/models"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

type LoginReq struct {
	UserName string `json:"user_name"`
	Passwd   string `json:"password"`
}

type LoginResp struct {
	models.User
	Token string   `json:"token,omitempty" yaml:"token"`
	Menus []string `json:"menus,omitempty"`
}

// 用户登录
func Login() gin.HandlerFunc {
	return func(c *gin.Context) {
		lr := new(LoginReq)
		if err := c.ShouldBindJSON(lr); err != nil {
			helper.SetHttpMsgResp(c, helper.HttpCodeValidateFail, helper.Translate(err))
			return
		}

		// 登录
		ur, err := models.NewUser(nil).Where(&models.User{UserName: lr.UserName}).First()
		if err != nil {
			helper.SetHttpMsgResp(c, helper.HttpCodeInternalFail, errors.WithMessage(err, "db query fail").Error())
			return
		}
		if helper.MD5Bytes([]byte(lr.Passwd)) != ur.Passwd {
			helper.SetHttpMsgResp(c, helper.HttpCodeInternalFail, "passwd do not matched")
			return
		}

		// 设置返回值
		id := strconv.Itoa(int(ur.ID))
		resp := LoginResp{
			User: *ur,
			Token: helper.GenerateToken(id),	
		}
		data,_ := json.Marshal(resp)
		helper.SetHttpDataResp(c,string(data))
	}
}
